package org.kadicon.android.network;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import org.kadicon.android.network.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MyNetwork extends Activity {

	private EditText ipEditText;
	private EditText portEditText;
	private Button connectButton;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Thread sThread = new Thread(new SocTCPServer());

		sThread.start();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
		}

		ipEditText = (EditText) findViewById(R.id.IPEditText);
		ipEditText.setText(SocTCPServer.SERVERIP);

		portEditText = (EditText) findViewById(R.id.PortEditText);
		portEditText.setText(String.valueOf(SocTCPServer.SERVERPORT));

		connectButton = (Button) findViewById(R.id.ConnectButton);
		connectButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String ip = ipEditText.getText().toString();
				int port = Integer.parseInt(portEditText.getText().toString());
				Socket socket = null;

				try {
					socket = new Socket(ip, port);
					BufferedWriter bufferedWriter = new BufferedWriter(
							new OutputStreamWriter(socket.getOutputStream()));
					bufferedWriter.write("MyNetwork");
					bufferedWriter.flush();
					bufferedWriter.close();
					socket.close();
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

	}
}